package com.meiqiongproperty.yiguanjia.fragment.personalCenter;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alipay.android.phone.mrpc.core.NetworkUtils;
import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.meiqiongproperty.yiguanjia.R;
import com.meiqiongproperty.yiguanjia.activity.GenericFragmentActivity;
import com.meiqiongproperty.yiguanjia.activity.MainActivity;
import com.meiqiongproperty.yiguanjia.databinding.PersonalCenterLayoutBinding;
import com.meiqiongproperty.yiguanjia.db.utils.DBUserUtils;
import com.meiqiongproperty.yiguanjia.fragment.BaseFragment;
import com.meiqiongproperty.yiguanjia.fragment.user.LoginFragment;
import com.meiqiongproperty.yiguanjia.http.api.ApiService;
import com.meiqiongproperty.yiguanjia.http.interfaces.IHttpCallback;
import com.meiqiongproperty.yiguanjia.http.interfaces.SimpleHttpCallback;
import com.meiqiongproperty.yiguanjia.http.sendJsonModel.SendLoginOut;
import com.meiqiongproperty.yiguanjia.http.sendJsonModel.UpPortraitBean;
import com.meiqiongproperty.yiguanjia.httpbean.user.ForGetpassword;
import com.meiqiongproperty.yiguanjia.ui.dialog.PersonalCenterAlertDialog;
import com.meiqiongproperty.yiguanjia.utils.LogUtil;
import com.meiqiongproperty.yiguanjia.utils.Utils;
import com.meiqiongproperty.yiguanjia.utils.cache.ACache;
import com.meiqiongproperty.yiguanjia.utils.image.ImageHelper;
import com.meiqiongproperty.yiguanjia.utils.phoneUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 个人中心
 *
 * @version V1.0
 * @packge com.meiqiongproperty.yiguanjia.fragment.home
 * @UserChenJing
 * @Date2017/4/22
 */

public class MyInformationFragment extends BaseFragment {
    PersonalCenterLayoutBinding binding;
    private List<LocalMedia> selectList = new ArrayList<>();
    ACache aCache;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.personal_center_layout, container, false);
        binding.setClick(this);
        aCache=ACache.get(getActivity());

        binding.personalCenterUsername.setText(Utils.getUserRealName(getActivity()));
        binding.Point.setText(DBUserUtils.getUserInfo(getActivity()).getPoint());
        binding.personalCenterAddress.setText(DBUserUtils.getmDefaultHouse(getActivity()).getCommunityName().toString());


        if (DBUserUtils.getUserInfo(getActivity()).getAvatar()==null){
            Glide.with(getActivity()).load(R.mipmap.img_header_portrait).into(binding.userimg);
        }else{
            Glide.with(getActivity()).load(DBUserUtils.getUserInfo(getActivity()).getAvatar()).into(binding.userimg);
        }
        return binding.getRoot();
    }


    /**
     * 头像点击
     */
    public void headImageClick(View view) {
        PictureSelector.create(getActivity())
                .openGallery(PictureMimeType.ofImage())
                .maxSelectNum(1)
                .minSelectNum(1)
                .selectionMode(PictureConfig.MULTIPLE)
                .previewImage(true)
                .compressGrade(Luban.THIRD_GEAR)
                .isCamera(true)
                .enableCrop(false)
                .compress(true)
                .compressMode(PictureConfig.LUBAN_COMPRESS_MODE)
                .glideOverride(160, 160)
                .previewEggs(true)
                .circleDimmedLayer(true)
                .withAspectRatio(1,1)
                .hideBottomControls(false)
                .isGif(false)
                .freeStyleCropEnabled(true)
                .showCropFrame(false)
                .showCropGrid(false)
                .openClickSound(true)
                .selectionMedia(selectList)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    /**
     * 积分
     */
    public void totalPointsClick(View view) {
        if (Utils.isFastDoubleClick()) {
            return;
        }
    }

    /**
     * 订单
     */
    public void personalCenterOrderClick(View view) {
        if (Utils.isFastDoubleClick()) {
            return;
        }
        MainActivity activity = (MainActivity) getActivity();
        activity.select(1);
    }

    /**
     * 联系管家
     */
    public void contactStewardClick(View view) {
        if (Utils.isFastDoubleClick()) {
            return;
        }
        if (DBUserUtils.getmDefaultHouse(getActivity()).getButlerPhone().length()>1){
            PersonalCenterAlertDialog dialog = new PersonalCenterAlertDialog(getActivity());
            dialog.builder().setCanceledOnTouchOutside(false).setMsg("粗心的管家忘记留号码了... ")
                    .setPositiveButton("确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                        }
                    }).show();
        }else {

        PersonalCenterAlertDialog dialog = new PersonalCenterAlertDialog(getActivity());
        dialog.builder().setCanceledOnTouchOutside(false).setMsg(Utils.getPropertyPhoneNumber(getActivity()))
                .setPositiveButton("呼叫", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        phoneUtils.goNativeCall(getActivity(), Utils.getPropertyPhoneNumber(getActivity()));
                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
        }
    }

    /**
     * 修改密码
     */
    public void modifyPwdClick(View view) {
        if (Utils.isFastDoubleClick()) {
            return;
        }
        GenericFragmentActivity.start(getActivity(), ModifyPwdFragment.class, new Bundle());
    }

    /**
     * 关于我们
     */
    public void aboutClick(View view) {
        if (Utils.isFastDoubleClick()) {
            return;
        }
        GenericFragmentActivity.start(getActivity(), AboutFragment.class, new Bundle());
    }

    /**
     * 退出登录
     */
    public void exitLoginClick(View view) {
        if (Utils.isFastDoubleClick()) {
            return;
        }
        PersonalCenterAlertDialog dialog = new PersonalCenterAlertDialog(getActivity());
        dialog.builder().setCanceledOnTouchOutside(false).setMsg("退出登录")
                .setPositiveButton("是", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (NetworkUtils.isNetworkAvailable(getActivity())){
                            LoginOut();
                        }else{
                            if (DBUserUtils.isLoginOut(getActivity())) {
                                GenericFragmentActivity.start(getActivity(), LoginFragment.class, new Bundle());
                            }
                        }
                    }
                }).setNegativeButton("否", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    /**
     * 登录退出
     */
    public void LoginOut() {
        SendLoginOut loginOut = new SendLoginOut();
        loginOut.setToken(DBUserUtils.getUserInfo(getActivity()).getToken());
        ApiService.logout(getActivity(), new SimpleHttpCallback<ForGetpassword>() {
            @Override
            public void onNext(ForGetpassword smSCode) {
                Toast.makeText(getActivity(), "退出登录成功", Toast.LENGTH_LONG).show();
                if (DBUserUtils.isLoginOut(getActivity())) {
                    GenericFragmentActivity.start(getActivity(), LoginFragment.class, new Bundle());
                    getActivity().finish();
                }
            }

            @Override
            public void onError(int code, String message) {
                super.onError(code, message);
                if (DBUserUtils.isLoginOut(getActivity())) {
                    GenericFragmentActivity.start(getActivity(), LoginFragment.class, new Bundle());
                    getActivity().finish();
                }
            }
        }, Utils.getRequestBody(loginOut));
        LogUtil.d("LoginOut===============>" + DBUserUtils.isLoginOut(getActivity()));
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.d("onActivityResult:");
        if (resultCode == getActivity().RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    LogUtil.d("onActivityResult:" + selectList.size());
                    Bitmap bitmap= BitmapFactory.decodeFile(selectList.get(0).getPath());
                    binding.userimg.setImageBitmap(ImageHelper.toRoundBitmap(bitmap));
                    aCache.put("headImage",selectList.get(0).getPath());
                    UpPortraitBean upPortraitBean=new UpPortraitBean();
                    upPortraitBean.setToken(Utils.getToken(getActivity()));
                    upPortraitBean.setImages1(new File(selectList.get(0).getPath()));

                    ApiService.upPortrait(getActivity(), new IHttpCallback<ForGetpassword>() {
                        @Override
                        public void onNext(ForGetpassword forGetpassword) {

                        }

                        @Override
                        public void onError(int code, String message) {

                        }
                    },Utils.getRequestBody(upPortraitBean));
                    break;
            }
        }
    }
}

